package nickthissen.iracing.common;

import android.content.Context;
import android.widget.Toast;

import java.util.ArrayList;

import nickthissen.iracing.datamodels.FavThreadsResult;
import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.datamodels.StringArrayResult;
import nickthissen.iracing.datamodels.User;
import nickthissen.iracing.networking.Networking;

/**
 * Created by Nick on 20-5-13.
 */
public class Donations
{
    private static ArrayList<String> donatedNames = new ArrayList<String>();

    public static void initialize(Context context)
    {
        donatedNames = PrivateStore.getDonations(context);
    }

    public static boolean hasDonated(String username)
    {
        return donatedNames.contains(username);
    }

    public static void load(Context context)
    {
        Task<Void> t = new Task<Void>(context, loader);
        t.execute();
    }

    private static void setDonations(Context context, ArrayList<String> names)
    {
        if (names.size() > 0)
        {
            donatedNames.clear();
            donatedNames.addAll(names);

            PrivateStore.saveDonations(context, donatedNames);
        }
    }

    private static DataLoader<Void> loader = new DataLoader<Void>()
    {
        @Override
        public Result getData(Void in)
        {
            StringArrayResult result = Networking.getDonations(this.getContext());
            if (result != null && result.Success)
            {
                return Result.ok(result.Object);
            }
            return Result.failed();
        }

        @Override
        public void onFinished(Result out)
        {
            if (out == null) out = Result.failed();
            if (out.Success)
            {
                setDonations(this.getContext(), (ArrayList<String>)out.Object);
            }
        }
    };
}
